package com.zhao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhao.bean.Employee;
import com.zhao.bean.PageParam;
import com.zhao.dao.EmployeeDao;
import com.zhao.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
//添加事务的注解，如果service的方法出现了异常，那么就回滚事务。
// 其实不加注解，数据也会跑到数据库去，是因为mybatisplus背后添加的时候使用的是自动提交的功能。j
@Transactional
@Service
public class EmployeeControllerImpl implements EmployeeService {
    @Autowired
    private EmployeeDao dao;

    //登录
    @Override
    public Employee login(Employee employee) {
        //创建Lmbda对象。设置组装查询条件。
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();

        //使用MD5对密码进行加密后再存放进入数据库
        String s = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        System.out.println(s);
        //设置组装查询条件
        lqw.eq(Employee::getUsername,employee.getUsername());
        lqw.eq(Employee::getPassword,s);

        Employee em = dao.selectOne(lqw);
        return em;
    }

    //添加员工
    @Override
    public int add(Employee employee) {

        return dao.insert(employee);
    }
    //分页
    @Override
    public IPage<Employee> find(PageParam param) {
        //设置查询条件
        LambdaQueryWrapper<Employee> qw=new LambdaQueryWrapper<>();
        //设置模糊查询
        qw.like(param.getName()!=null,Employee::getName,param.getName());

        Page<Employee> p=new Page<Employee>(param.getPage(),param.getPageSize());

        IPage<Employee> employeePage = dao.selectPage(p, qw);
        System.out.println("employeePage.getTotal() = " + employeePage.getTotal());
        return employeePage;
    }

    @Override
    public int update(Employee employee) {

        return dao.updateById(employee);
    }
}
